<?php
include_once (SYSTEM.'/Route.php');

class URLPattern
{
	public $Pattern;
	public $DefaultController;
	public $DefaultAction;
	public $Part;
	public $NumberPart;
	
	public $ExtraParam = array();
	
	public function __construct($pattern, $defaultController, $defaultAction, $defaultParameter = array())
	{
		$this->Pattern = $pattern;
		$this->Part = explode('/', $pattern);
		$this->NumberPart = count($this->Part);		
		
		$this->DefaultController = $defaultController;
		$this->DefaultAction = $defaultAction;
				
		foreach($defaultParameter as $key =>$value)
		{
			$this->ExtraParam[$key] = $value;
		}		
	}
	
	public function ValidateUrlPattern($partsOfUrl)
	{		
		$n = count($partsOfUrl);
		$controller = $this->DefaultController;
		$action = $this->DefaultAction;
		$isMatch = true;
		
		for($i = 0; $i<$n; $i++)
		{			
			$part = $this->Part[$i];
			
			if($part[0] == '{')
			{				
				$item = substr($this->Part[$i], 1,-1);
				if($item == 'Controller')
				{
					$controller = ucfirst(strtolower($partsOfUrl[$i]));
				}
				else if($item == 'Action')
				{
					$action = ucfirst(strtolower($partsOfUrl[$i]));
				}
				else 
				{					
					$this->ExtraParam[$item] = $partsOfUrl[$i];
				}
			}
			else if (strcasecmp($part, $partsOfUrl[$i]) != 0)
			{				
				$isMatch = false;
				break;
			}	
		}
		
		if(!$isMatch)
		{
			return null;
		}
		
		$route = new Route($controller.'Controller', $action, $this->ExtraParam);
		return $route;
	}
}
